package unsafeExp;

/**
 * @program: javase
 * @description: 抢票
 * @author: lld
 * @create: 2021-03-21 19:46
 **/
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        new Thread(station,"x").start();
        new Thread(station,"y").start();
        new Thread(station,"z").start();
    }
}
class BuyTicket implements Runnable{
    private int num=10;
    private boolean flag=true;
//使用synchronized解决
    public synchronized void buy() throws InterruptedException {
       if(num<=0){
           flag=false;
           return;
       }
       //模拟延迟
//        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName()+" buy "+num--);
    }

    @Override
    public void run() {
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
